import { initRoutes, type RouteConfig } from '@/routers/helper';
import type { ReactNode } from 'react';
import { create } from 'zustand';
import { devtools, persist, createJSONStorage } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
export type MenuItem = {
  key: string;
  icon?: ReactNode;
  label: string;
  children?: MenuItem[];
};

type TagItem = {
  title: string;
  path: string;
};

type MenuState = {
  menus: MenuItem[];
  indexPath: string[];
  tags: TagItem[];
};

type MenuAction = {
  initMenus: (routes: RouteConfig[]) => void;
};

const immerResult = immer<MenuState & MenuAction>(set => ({
  menus: [],
  indexPath: [],
  tags: [],
  initMenus: routes =>
    set(state => {
      const { menus, indexPath } = initRoutes(routes);
      state.menus = menus;
      state.indexPath = indexPath;
    }),
}));

const persistResult = persist(immerResult, {
  name: 'menu-store',
  storage: createJSONStorage(() => localStorage),
});

const devtoolsResult = devtools(persistResult, {
  name: 'Menu Store',
  enabled: true,
});

export const useMenuStore = create<MenuState & MenuAction>()(devtoolsResult);
